﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using HerGoS.Administration.Entities;
using HerGoS.Administration.Engine;

namespace HerGoS.WebUI.GlobalUI
{
    public class SiteController
    {
        static Dictionary<string, Modulo> pages = new Dictionary<string, Modulo>();

        public static string GetCurrentUrl()
        {
            string url = HttpContext.Current.Request.Url.GetComponents(UriComponents.Path, UriFormat.Unescaped);
            return url;
        }

        public static string GetVirtualPath(string physicalPath)
        {
            if (!physicalPath.StartsWith(HttpRuntime.AppDomainAppPath))
            {
                throw new InvalidOperationException("Physical path is not within the application root");
            }

            return physicalPath.Substring(HttpRuntime.AppDomainAppPath.Length).Replace("\\", "/");
        }

        public static void LoadPagesModules()
        {
            //Obtiene todas las paginas del sitio (aspx)
            String[] Files = System.IO.Directory.GetFiles(HttpRuntime.AppDomainAppPath, "*.aspx", System.IO.SearchOption.AllDirectories);

            //Reemplaza el path fisico por el virtual y lo agrega a la lista
            foreach (string file in Files)
            {
                pages.Add(SiteController.GetVirtualPath(file).ToLower(), null);
            }

            GestorModulo.SetModulosPages(pages);
        }

        /// <summary>
        /// Obtiene el modulo de la pagina actual
        /// </summary>
        /// <returns>Modulo</returns>
        public static Modulo GetCurrentModulo()
        {
            string url = GetCurrentUrl().ToLower();
            return GetModulo(url);
        }
        
        public static Modulo GetModulo(string url)
        {
            string key = url.ToLower();
            if (pages.ContainsKey(key))
                return pages[key];
            else
                return null;
        }
    }
}